#include "bitmapdef.h"

boolean set_bit(volatile address map, int byte_size, int bit)
{
    volatile word *array = CAST_AS(volatile word *, map);
    int index, offset, limit;
    if (4 == sizeof(word))
    {
        index = bit >> 5;
        offset = bit & 0b11111;
        limit = byte_size >> 2;
    }
    else
    {
        // regard as 64 bit
        index = bit >> 6;
        offset = bit & 0b111111;
        limit = byte_size >> 3;
    }
    if (index >= limit)
    {
        return False;
    }
    array[index] |= ((1 << offset));
    return True;
}

boolean clear_bit(volatile address map, int byte_size, int bit)
{
    volatile word *array = CAST_AS(volatile word *, map);
    int index, offset, limit;
    if (4 == sizeof(word))
    {
        index = bit >> 5;
        offset = bit & 0b11111;
        limit = byte_size >> 2;
    }
    else
    {
        // regard as 64 bit
        index = bit >> 6;
        offset = bit & 0b111111;
        limit = byte_size >> 3;
    }
    if (index >= limit)
    {
        return False;
    }
    array[index] &= (~(1 << offset));
    return True;

}

boolean set_char_as(volatile address map, int byte_size, int id, unsigned char v)
{
    volatile word *array = CAST_AS(volatile word *, map);
    int index, offset, limit;
    if (4 == sizeof(word))
    {
        index = id >> 2;
        offset = id & 0b11;
        limit = byte_size >> 2;
    }
    else
    {
        index = id >> 3;
        offset = id & 0b111;
        limit = byte_size >> 3;
    }
    if (index >= limit)
    {
        return False;
    }
    array[index] |= (v << (offset + 3));
    return True;
}